package net.wanho.interceptor;

import cn.hutool.core.util.StrUtil;
import net.wanho.constant.UserConstant;
import net.wanho.exception.LoginAuthException;
import net.wanho.util.CurrentUtils;
import net.wanho.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(StrUtil.isEmpty(token)){
            throw new LoginAuthException("请先登录再操作" + request.getRequestURI());
        }
        token = token.replace("Bearer ", "");
        if(!JwtUtil.valid(token)){
            throw new LoginAuthException("非法的token" + request.getRequestURI());
        }
        Integer userId = JwtUtil.parseInteger(token, UserConstant.USER_ID);
        CurrentUtils.setId(userId);
        return true;
    }
}
